package com.weds.frame.core.util;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Description: redis工具类
 * Author: LiuWenQing
 * Datetime: 2023/3/13 15:22
 */
@Component
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public class RedisUtil {

    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public final static long NOT_EXPIRE = -1L;

    public String getString(String key) {
        try {
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
        return null;
    }

    public void put(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
    }

    public void put(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
    }

    public void put(String key, Object value, long timeout, TimeUnit unit) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, unit);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
    }

    public void put(String key, String value, long timeout, TimeUnit unit) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
    }

    public Set<String> getKeys(String pattern) {
        try {
            return stringRedisTemplate.keys(pattern);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
        return null;
    }

    public void del(String key) {
        try {
            stringRedisTemplate.delete(key);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
    }

    public void dels(Collection<String> keys) {
        try {
            stringRedisTemplate.delete(keys);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
    }

    /**
     * 获取当前路径下，所有key
     *
     * @param pattern 路径（可以是模糊路径）
     * @author tjy
     **/
    public Set<String> getScanKeys(String pattern) {
        return stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> tmpKeys = new HashSet<>();
            ScanOptions options;
            options = ScanOptions.scanOptions().match(pattern).count(5000).build();
            // 迭代一直查找，直到找到redis中所有满足条件的key为止(cursor变为0为止)
            Cursor<byte[]> cursor = connection.scan(options);
            while (cursor.hasNext()) {
                tmpKeys.add(new String(cursor.next()));
            }
            return tmpKeys;
        });
    }

    public Object get(String key, long expire) {
        Object value = redisTemplate.opsForValue().get(key);
        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
        return value;
    }

    public Long size(String key){
        if(!keyExist(key)){
            return 0L;
        }
        return redisTemplate.opsForList().size(key);
    }

    public void leftPush(String key, Object value) {
        leftPush(key, value, NOT_EXPIRE);
    }

    public void leftPush(String key, Object value, long expire) {
        redisTemplate.opsForList().leftPush(key, value);

        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
    }

    public Object rightPop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    /**********右(下)进左(上)出*********/
    public void rightPush(String key, Object value) {
        rightPush(key, value, NOT_EXPIRE);
    }

    public void rightPush(String key, Object value, long expire) {
        redisTemplate.opsForList().rightPush(key, value);

        if (expire != NOT_EXPIRE) {
            expire(key, expire);
        }
    }

    public List<Object> range(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public Object leftPop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    public Object get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void send(String channel, String msg) {
        try {
            stringRedisTemplate.convertAndSend(channel, msg);
        } catch (Exception e) {
            ExceptionUtil.printStackTrace(e);
        } finally {
            closeTransactionSupport();
        }
    }

    public Long increment(String key, Integer self) {
        Long increment = getStringRedisTemplate().opsForValue().increment(key, self);
        if (increment == Long.MAX_VALUE) {
            del(key);
            increment = getStringRedisTemplate().opsForValue().increment(key, self);
        }
        return increment;
    }

    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

//    /**
//     * 缓存List数据
//     *
//     * @param key 缓存的键值
//     * @return 缓存的对象
//     */
//    public <T> long setCacheList(final String key, final List<T> dataList) {
//        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
//        return count == null ? 0 : count;
//    }
//
//    /**
//     * 获得缓存的list对象
//     *
//     * @param key 缓存的键值
//     * @return 缓存键值对应的数据
//     */
//    public <T> List<T> getCacheList(final String key) {
//        return redisTemplate.opsForList().range(key, 0, -1);
//    }


    public <T> void setCacheList(final String key, final List<T> dataList){
        if(dataList == null || dataList.isEmpty())
            return;

        redisTemplate.opsForValue().set(key, JSON.toJSONString(dataList));
        return;
    }

    public <T> List<T> getCacheList(final String key, Class<T> clz){
        return redisTemplate.opsForValue().get(key) == null?
                new ArrayList<>(): JSON.parseArray(redisTemplate.opsForValue().get(key).toString(),clz);
    }
    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    public <T> Long removeCacheSetValue(final String key, T value) {
        SetOperations setOperations = redisTemplate.opsForSet();
        return setOperations.remove(key, value);
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }

    public Boolean keyExist(String key) {

        return redisTemplate.hasKey(key);
    }

    public void addCacheSet(String key, Object... vals) {
        redisTemplate.opsForSet().add(key, vals);
    }

    private void closeTransactionSupport() {
        RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
    }
}
